package com.gomore.opple.module.orderpay;

import android.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.Action;
import com.gomore.opple.model.EventActionFinish;
import com.gomore.opple.model.EventLottery;
import com.gomore.opple.model.EventMine;
import com.gomore.opple.model.EventScanCode;
import com.gomore.opple.model.LotteryModel;
import com.gomore.opple.model.OrderPromotionModel;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.orderpay.adapter.ConditionAdapter;
import com.gomore.opple.module.orderpay.adapter.GoodAdpater;
import com.gomore.opple.module.orderpay.adapter.OrderPromotionAdapter;
import com.gomore.opple.rest.order.OrderBill;
import com.gomore.opple.rest.order.OrderPayRequest;
import com.gomore.opple.rest.order.PromotionGoods;
import com.gomore.opple.rest.order.RedPackageDetail;
import com.gomore.opple.rest.order.RsOrderShareResponse;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.utils.DateUtil;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.web.cgform.order.entity.TOOrderEntity;
import com.gomore.opple.web.cgform.orderdetail.entity.TOOrderdetailEntity;
import com.gomore.opple.web.cgform.orderpromotion.entity.TOOrderPromotionEntity;
import com.gomore.opple.web.system.pojo.TOReseller;
import com.gomore.opple.widgets.MyListView;
import com.gomore.opple.widgets.XCRoundRectImageView;
import com.gomore.opple.widgets.dialog.ConfirmDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/**
 * Created by robot
 */
public class OrderPayFragment extends BaseFragment implements OrderPayContract.View {

    @Bind(R.id.back)
    LinearLayout back;
    @Bind(R.id.share)
    ImageView share;
    @Bind(R.id.return_back)
    TextView return_back;
    @Bind(R.id.pay_order)
    TextView pay_order;
    @Bind(R.id.share_relative)
    RelativeLayout share_relative;
    @Bind(R.id.weixin)
    ImageView weixin;
    @Bind(R.id.weixincirle)
    ImageView weixincirle;
    @Bind(R.id.weibo)
    ImageView weibo;

    //订单信息
    @Bind(R.id.order_number)
    TextView order_number;
    @Bind(R.id.order_date)
    TextView order_date;
    @Bind(R.id.order_state)
    TextView order_state;
    @Bind(R.id.order_guide)
    TextView order_guide;
    //客户信息
    @Bind(R.id.customer_icon)
    XCRoundRectImageView customer_icon;
    @Bind(R.id.customer_name)
    TextView customer_name;
    @Bind(R.id.customer_mobile)
    TextView customer_mobile;
    @Bind(R.id.customer_company)
    TextView customer_company;
    @Bind(R.id.customer_address)
    TextView customer_address;
    //收货信息
    @Bind(R.id.receiver_name)
    TextView receiver_name;
    @Bind(R.id.receiver_mobile)
    TextView receiver_mobile;
    @Bind(R.id.receiver_address)
    TextView receiver_address;
    //商品清单
    @Bind(R.id.good_my_list_view)
    MyListView good_my_list_view;
    @Bind(R.id.number)
    TextView number;
    @Bind(R.id.total)
    TextView total;
    @Bind(R.id.total_detail)
    TextView total_detail;
    GoodAdpater goodAdpater;
    //附件信息
    @Bind(R.id.open_invoice)
    TextView open_invoice;
    @Bind(R.id.invoice_header)
    TextView invoice_header;
    @Bind(R.id.invoice_type)
    TextView invoice_type;
    @Bind(R.id.pay_method)
    TextView pay_method;
    //订单促销记录
    @Bind(R.id.order_promotion_linear)
    View order_promotion_linear;
    @Bind(R.id.order_promotion_my_list_view)
    MyListView order_promotion_my_list_view;
    OrderPromotionAdapter orderPromotionAdapter;

    @Bind(R.id.scroll_view)
    ScrollView scroll_view;


    private OrderPayContract.Presenter mPresenter;
    private String orderId;
    private String orderState;
    private TOOrderEntity allOrder;
    private OrderBill allOrderBill;
    private String payMethodCode, openCashCode, cashTypeCode;
    private UMShareListener umShareListener;
    private int viewType = 1;//1 分享不可见，支付，撤销可见；2，分享可见，支付，撤销不可见；3 都不可见
    private String promotionType = GlobalConstant.PromotionType.PROMOTIONSERVICE;
    private LotteryModel lotteryModel;

    public static OrderPayFragment getInstance() {
        return new OrderPayFragment();
    }

    @Override
    protected void initalizeData() {
        super.initalizeData();
        EventBus.getDefault().register(this);
        if (getArguments() != null && getArguments().getString(IntentStart.ORDERID) != null) {
            orderId = getArguments().getString(IntentStart.ORDERID);
            orderState = getArguments().getString(IntentStart.ORDERSTATE);
            if (orderState == null) {
                return;
            }
            if (orderState.equals(GlobalConstant.OrderState.UNPAID)) {
                viewType = 1;
                promotionType = GlobalConstant.PromotionType.PROMOTIONSERVICE;
            } else if (orderState.equals(GlobalConstant.OrderState.CANCELED)) {
                viewType = 3;
                promotionType = GlobalConstant.PromotionType.PROMOTION;
            } else {
                if (orderState.equals(GlobalConstant.OrderState.PAID) || orderState.equals(GlobalConstant.OrderState.COMPLETED)) {
                    viewType = 2;
                } else {
                    viewType = 3;
                }
                promotionType = GlobalConstant.PromotionType.ORDERPROMOTIONSERVICE;
            }
            mPresenter.getOrder(orderId, promotionType, viewType);
        }
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_order_pay;
    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
        umShareListener = new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                //分享开始的回调
            }

            @Override
            public void onResult(SHARE_MEDIA platform) {
                Log.d("plat", "platform" + platform);
                showMessage(" 分享成功啦");
            }

            @Override
            public void onError(SHARE_MEDIA platform, Throwable t) {
                String string = "分享失败啦";
                if (t != null) {
                    if (t.getMessage() != null && t.getMessage().contains("2008")) {
                        string = "没有安装应用";
                    }
                    Log.e("throw", "throw:" + t.getMessage());
                }
                showMessage(string);
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                showMessage(" 分享取消了");
            }
        };
    }


    @Override
    public void setPresenter(OrderPayContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void showContentView(OrderBill orderBill, int isView) {
        if (isView == 1) {
            share.setVisibility(View.GONE);
            return_back.setVisibility(View.VISIBLE);
            pay_order.setVisibility(View.VISIBLE);
        } else if (isView == 2) {
            share.setVisibility(View.VISIBLE);
            return_back.setVisibility(View.GONE);
            pay_order.setVisibility(View.GONE);
        } else {
            share.setVisibility(View.GONE);
            return_back.setVisibility(View.GONE);
            pay_order.setVisibility(View.GONE);
        }
        if (orderBill == null) {
            return;
        }
        allOrderBill = orderBill;
        TOOrderEntity order = orderBill.getOrder();
        if (order == null) {
            return;
        }
        allOrder = order;
        showOrderMessage(order);
        showAddressMessage(order);
        showAttachmentMessage(order);
        List<TOOrderdetailEntity> toOrderdetailEntityList = orderBill.getOrderdetailList();
        if (toOrderdetailEntityList == null) {
            return;
        }
        showGoodMessage(order, toOrderdetailEntityList);
        scroll_view.smoothScrollTo(0, 20);
    }

    @Override
    public void showConsumerView(TOConsumerEntity toConsumerEntity) {
        int height = DensityUtil.dip2px(getActivity(), 80);
        String url = "demo";
        if (toConsumerEntity.getPicture() != null) {
            url = toConsumerEntity.getPicture();
        }
        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .centerCrop()
                .override(height, height)
                .placeholder(R.mipmap.consumer_icon)
                .into(customer_icon);
        if (toConsumerEntity.getName() != null) {
            customer_name.setText(toConsumerEntity.getName());
        }
        if (toConsumerEntity.getMobile() != null) {
            customer_mobile.setText(toConsumerEntity.getMobile());
        }
        if (toConsumerEntity.getCompany() != null) {
            customer_company.setText(toConsumerEntity.getCompany());
        }
        if (toConsumerEntity.getAddress() != null) {
            customer_address.setText(toConsumerEntity.getAddress());
        }
    }

    @Override
    public void showConditionSelect() {
        showConditionDialog();
    }

    @OnClick({R.id.back, R.id.return_back, R.id.share, R.id.pay_order,
            R.id.weixin, R.id.weixincirle, R.id.weibo, R.id.share_relative})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                getActivity().finish();
                break;
            case R.id.return_back:
                //确定框
                ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
                ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
                final String title = "提示";
                String message = "确定撤销订单？";
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        setUnSelect(mPresenter.getConsumerActionData());
                        viewType = 3;
                        promotionType = GlobalConstant.PromotionType.PROMOTION;
                        mPresenter.updateOrderState(allOrder.getOrderNumber(), GlobalConstant.OrderState.UNPAID,
                                GlobalConstant.OrderState.CANCELED, promotionType, viewType);
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                    }
                };
                DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
                break;
            case R.id.share:
                mPresenter.shareOrder(allOrder.getOrderNumber());
                break;
            case R.id.pay_order:
                showPayDialog(allOrder);
                break;
            case R.id.weixin:
                getshare(1, mPresenter.getShareUrl());
                break;
            case R.id.weixincirle:
                getshare(2, mPresenter.getShareUrl());
                break;
            case R.id.weibo:
                getshare(3, mPresenter.getShareUrl());
                break;
            case R.id.share_relative:
                if (share_relative.getVisibility() == View.VISIBLE) {
                    share_relative.setVisibility(View.GONE);
                }
                break;
        }
    }

    //展示订单信息
    private void showOrderMessage(TOOrderEntity order) {
        if (order.getOrderNumber() != null) {
            order_number.setText(order.getOrderNumber());
        }
        if (order.getCreateDate() != null) {
            order_date.setText(DateUtil.formatDate(order.getCreateDate(), DateUtil.DATE_FORMATTER_2));
        }
        if (order.getOrderState() != null) {
            order_state.setText(GlobalConstant.OrderState.getStateNameByCode(order.getOrderState()));
            order_state.setTextColor(getActivity().getResources().getColor(GlobalConstant.OrderState.getColorByCode(order.getOrderState())));
        }
        if (order.getGuideName() != null) {
            order_guide.setText(order.getGuideName());
        }
    }

    //展示收货地址
    private void showAddressMessage(TOOrderEntity order) {
        if (order.getReceiverName() != null) {
            receiver_name.setText(order.getReceiverName());
        }
        if (order.getReceiverMobile() != null) {
            receiver_mobile.setText(order.getReceiverMobile());
        }
        if (order.getReceiverAddress() != null) {
            receiver_address.setText(order.getReceiverAddress());
        }
    }

    //展示商品信息
    private void showGoodMessage(TOOrderEntity order, List<TOOrderdetailEntity> toOrderdetailEntityList) {
        goodAdpater = new GoodAdpater(getActivity(), toOrderdetailEntityList);
        good_my_list_view.setAdapter(goodAdpater);
        number.setText("×" + order.getGoodsNum());
        BigDecimal bigDecimal = BigDecimalUtils.forMate(order.getOrderPrice());
        total.setText("¥" + bigDecimal.toString());
    }

    //展示附件信息
    private void showAttachmentMessage(TOOrderEntity order) {
        if (!TextUtils.isEmpty(order.getIsBill())) {
            open_invoice.setText(order.getIsBill());
        }
        if (!TextUtils.isEmpty(order.getBillTitle())) {
            invoice_header.setText(order.getBillTitle());
        }
        if (!TextUtils.isEmpty(order.getBillType())) {
            invoice_type.setText(order.getBillType());
        }
        if (!TextUtils.isEmpty(order.getPayType())) {
            pay_method.setText(order.getPayType());
        }
    }

    private void showConditionDialog() {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.condition_dialog, null);
        ListView listView = (ListView) layout.findViewById(R.id.list_view);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        TextView confirm = (TextView) layout.findViewById(R.id.confirm);
        ConditionAdapter conditionAdapter = new ConditionAdapter(getActivity(), mPresenter.getConsumerActionData());
        listView.setAdapter(conditionAdapter);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定框
                ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
                ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
                final String title = "提示";
                String message = "退出后此单不再享受促销";
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        setUnSelect(mPresenter.getConsumerActionData());
                        alertDialog.dismiss();
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                    }
                };
                DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doActions();
                alertDialog.dismiss();
            }
        });
    }

    //操作各种促销
    @Override
    public void doActions() {
        for (int i = 0; i < mPresenter.getConsumerActionData().size(); i++) {
            Action action = mPresenter.getConsumerActionData().get(i);
            if (action.isSelect() && !action.isUsed()) {
                if (action.getType().equals(GlobalConstant.consumerConditionType.LOTTERYACTION)) {
                    IntentStart.getInstance().startLotteryActivity(getActivity(), action.getLottery().getUuid(), allOrder.getOrderNumber(),
                            null, GlobalConstant.FragmentType.ORDERPAYFRAGMENT);
                    break;
                }
                if (action.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                    IntentStart.getInstance().startMipcaActivityCaptureActivity(getActivity(), GlobalConstant.FragmentType.ORDERPAYFRAGMENT);
                    break;
                }
                if (action.getType().equals(GlobalConstant.consumerConditionType.DEDUCTIONACTION)) {
                    action.setIsUsed(true);
                }
                if (action.getType().equals(GlobalConstant.consumerConditionType.DISCOUNTACTION)) {
                    action.setIsUsed(true);
                }
                if (action.getType().equals(GlobalConstant.consumerConditionType.GOODSACTION)) {
                    action.setIsUsed(true);
                }
            }
        }
    }

    //展示支付弹框
    private void showPayDialog(TOOrderEntity order) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.pay_dialog_bg, null);
        TextView total_number = (TextView) layout.findViewById(R.id.total_number);
        TextView total = (TextView) layout.findViewById(R.id.total);
        Spinner spinner_pay_method = (Spinner) layout.findViewById(R.id.spinner_pay_method);
        final RelativeLayout wei_xin_pay = (RelativeLayout) layout.findViewById(R.id.wei_xin_pay);
        final RelativeLayout zhifubao_pay = (RelativeLayout) layout.findViewById(R.id.zhifubao_pay);
        Spinner spinner_open_cash = (Spinner) layout.findViewById(R.id.spinner_open_cash);
        final Spinner spinner_cash_type = (Spinner) layout.findViewById(R.id.spinner_cash_type);
        final EditText cash_title = (EditText) layout.findViewById(R.id.cash_title);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        TextView confirm = (TextView) layout.findViewById(R.id.confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        payMethodCode = GlobalConstant.PayMethod.getCodeByName(GlobalConstant.PayMethod.payMethodList().get(0));
        openCashCode = GlobalConstant.OpenCash.getCodeByName(GlobalConstant.OpenCash.openCashList().get(0));
        cashTypeCode = GlobalConstant.CashType.getCodeByName(GlobalConstant.CashType.cashTypeList().get(0));
        //order对象为空则直接挂起
        if (order == null) {
            return;
        }
        //总数
        total_number.setText(order.getGoodsNum());
        //总金额(折算之后)
        BigDecimal bigDecimal = getFinalTotal(order.getOrderPrice());
        final BigDecimal bigDecimal1 = BigDecimalUtils.forMate(bigDecimal);
        total.setText("¥" + bigDecimal1.toString());
        //支付方式
        ArrayAdapter spinner_pay_method_adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, GlobalConstant.PayMethod.payMethodList());
        //设置样式
        spinner_pay_method_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_pay_method.setAdapter(spinner_pay_method_adapter);
        spinner_pay_method.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.gray));
                tv.setTextSize(14);
                payMethodCode = GlobalConstant.PayMethod.getCodeByName(GlobalConstant.PayMethod.payMethodList().get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //是否开发票
        ArrayAdapter spinner_open_cash_adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, GlobalConstant.OpenCash.openCashList());
        //设置样式
        spinner_open_cash_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_open_cash.setAdapter(spinner_open_cash_adapter);
        spinner_open_cash.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.gray));
                tv.setTextSize(14);
                openCashCode = GlobalConstant.OpenCash.getCodeByName(GlobalConstant.OpenCash.openCashList().get(position));
                //判断发票类型，与发票抬头是否可点击
                if (openCashCode.equals(GlobalConstant.OpenCash.NO_CODE)) {
                    spinner_cash_type.setEnabled(false);
                    cash_title.setEnabled(false);
                } else {
                    spinner_cash_type.setEnabled(true);
                    cash_title.setEnabled(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //发票类型
        ArrayAdapter spinner_cash_type_adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, GlobalConstant.CashType.cashTypeList());
        //设置样式
        spinner_cash_type_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_cash_type.setAdapter(spinner_cash_type_adapter);
        spinner_cash_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.gray));
                tv.setTextSize(14);
                cashTypeCode = GlobalConstant.CashType.getCodeByName(GlobalConstant.CashType.cashTypeList().get(position));
                if (cashTypeCode == null || cashTypeCode.equals(GlobalConstant.CashType.PERSON_CODE)) {
                    cash_title.setEnabled(false);
                } else {
                    cash_title.setEnabled(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        wei_xin_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payMethodCode = GlobalConstant.PayMethod.WEIXIN_CODE;
                mPresenter.getReseller(GlobalConstant.PayMethodOnLine.WEIXIN);
                wei_xin_pay.setBackgroundResource(R.mipmap.pay_select_bg);
                zhifubao_pay.setBackgroundResource(R.mipmap.pay_unselect_bg);
            }
        });

        zhifubao_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payMethodCode = GlobalConstant.PayMethod.ZHIFUBAO_CODE;
                mPresenter.getReseller(GlobalConstant.PayMethodOnLine.ZHIFUBAO);
                zhifubao_pay.setBackgroundResource(R.mipmap.pay_select_bg);
                wei_xin_pay.setBackgroundResource(R.mipmap.pay_unselect_bg);
            }
        });
        //判断发票类型，与发票抬头是否可点击
        if (openCashCode.equals(GlobalConstant.OpenCash.NO_CODE)) {
            cash_title.setEnabled(false);
            spinner_cash_type.setEnabled(false);
        } else {
            cash_title.setEnabled(true);
            spinner_cash_type.setEnabled(true);
        }
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                payMethodCode = null;
                openCashCode = null;
                cashTypeCode = null;
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OrderPayRequest orderPayRequest = new OrderPayRequest();
                orderPayRequest.setOrderNumber(allOrder.getOrderNumber());
                orderPayRequest.setOldstate(allOrder.getOrderState());
                orderPayRequest.setNewstate(GlobalConstant.OrderState.PAID);
                if (TextUtils.isEmpty(payMethodCode)) {
                    showMessage("请选择一种支付方式");
                    return;
                }
                if (openCashCode.equals(GlobalConstant.OpenCash.YES_CODE)) {
                    if (cashTypeCode == null) {
                        showMessage("请选择发票类型");
                        return;
                    }
                } else {
                    cashTypeCode = null;
                }
                orderPayRequest.setPayType(payMethodCode);
                orderPayRequest.setIsbill(openCashCode);
                orderPayRequest.setBillType(cashTypeCode);
                if (openCashCode.equals(GlobalConstant.OpenCash.YES_CODE) &&
                        cashTypeCode.equals(GlobalConstant.CashType.COMPANY)) {
                    if (TextUtils.isEmpty(cash_title.getText().toString().trim())) {
                        showMessage("请输入发票抬头");
                        return;
                    }
                }
                String billTitle = cash_title.getText().toString().trim();
                if (TextUtils.isEmpty(billTitle)) {
                    billTitle = null;
                }
                orderPayRequest.setBillTitle(billTitle);
                //总金额(折算之后)
                BigDecimal bigDecimal = getFinalTotal(allOrder.getOrderPrice());
                orderPayRequest.setRealAmount(BigDecimalUtils.forMate(bigDecimal));
                //后来添加(抵扣金额),不能为空
                orderPayRequest.setPromotionMoney(new BigDecimal(0));
                List<PromotionGoods> promotionGoodsList = new ArrayList<>();
                for (int i = 0; i < mPresenter.getConsumerActionData().size(); i++) {
                    Action action = mPresenter.getConsumerActionData().get(i);
                    if (action.isSelect() && action.isUsed()) {
                        //大转盘抽奖
                        if (action.getType().equals(GlobalConstant.consumerConditionType.LOTTERYACTION)) {
                            if (lotteryModel != null) {
                                orderPayRequest.setDrawId(lotteryModel.getDrawId());
                            }
                            orderPayRequest.setDrawPrority(action.getPriority());
                        }
                        //微信卡卷
                        if (action.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                            if (mPresenter.getWeChatData() != null) {
                                orderPayRequest.setWxcardNumber(mPresenter.getWeChatData().getPayNo());
                                orderPayRequest.setWxcardDenomation(new BigDecimal(mPresenter.getWeChatData().getDenomation()));
                            }
                            orderPayRequest.setWxCardPrority(action.getPriority());
                        }
                        //抵扣
                        if (action.getType().equals(GlobalConstant.consumerConditionType.DEDUCTIONACTION)) {
                            orderPayRequest.setPromotionMoney(new BigDecimal(action.getTotal()));
                            orderPayRequest.setDeductionPrority(action.getPriority());
                        }
                        //赠送商品
                        if (action.getType().equals(GlobalConstant.consumerConditionType.GOODSACTION)) {
                            PromotionGoods promotionGoods = new PromotionGoods();
                            promotionGoods.setGoods(action.getGoods());
                            promotionGoods.setPromotionNumber(new BigDecimal(action.getCount()));
                            promotionGoodsList.add(promotionGoods);
                            orderPayRequest.setGoodsPrority(action.getPriority());
                        }
                    }
                }
                orderPayRequest.setPromotionGoods(promotionGoodsList);
                List<RedPackageDetail> redPackageDetailList = new ArrayList<>();
                for (int j = 0; j < mPresenter.getGuideActionData().size(); j++) {
                    Action action = mPresenter.getGuideActionData().get(j);
                    if (action.getType().equals(GlobalConstant.guideConditionType.JDECARDACTION)) {
                        orderPayRequest.setJDEcardsPrority(action.getPriority());
                        orderPayRequest.setJdCardDenomation(action.getTotal());
                    }
                    if (action.getType().equals(GlobalConstant.guideConditionType.REDPACKAGEACTION)) {
                        RedPackageDetail redPackageDetail = new RedPackageDetail();
                        redPackageDetail.setMoney(new BigDecimal(action.getTotal()));
                        redPackageDetail.setPromotionBillNumber(action.getPromotionBillNumber());
                        redPackageDetail.setRedPrority("" + action.getPriority());
                        redPackageDetailList.add(redPackageDetail);
                    }
                    if (action.getType().equals(GlobalConstant.guideConditionType.LOTTERYACTION)) {
                        orderPayRequest.setLotteryId(action.getLottery().getUuid());
                    }
                }
                orderPayRequest.setRedPackageDetails(redPackageDetailList);
                viewType = 2;
                promotionType = GlobalConstant.PromotionType.ORDERPROMOTIONSERVICE;
                mPresenter.payOrder(orderPayRequest, allOrder.getOrderNumber(), promotionType, viewType);
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void showCodeDialog(String payMethod, TOReseller toReseller) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.code_dialog, null);
        ImageView cancel = (ImageView) layout.findViewById(R.id.cancel);
        TextView employee_name = (TextView) layout.findViewById(R.id.employee_name);
        ImageView code = (ImageView) layout.findViewById(R.id.code);
        TextView pay_method_text = (TextView) layout.findViewById(R.id.pay_method_text);
        LinearLayout step = (LinearLayout) layout.findViewById(R.id.step);
        ImageView step1 = (ImageView) layout.findViewById(R.id.step1);
        ImageView step2 = (ImageView) layout.findViewById(R.id.step2);
        ImageView step3 = (ImageView) layout.findViewById(R.id.step3);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        String url;
        if (toReseller.getDepartname() != null) {
            employee_name.setText(toReseller.getDepartname());
        }
        int intColor;
        if (payMethod.equals(GlobalConstant.PayMethodOnLine.WEIXIN)) {
            intColor = getActivity().getResources().getColor(R.color.green);
            url = toReseller.getWeixin();
            step1.setImageResource(R.mipmap.weixin_step1);
            step2.setImageResource(R.mipmap.weixin_step2);
            step3.setImageResource(R.mipmap.weixin_step3);
        } else {
            intColor = getActivity().getResources().getColor(R.color.blue);
            url = toReseller.getZhifubao();
            step1.setImageResource(R.mipmap.zhifubao_step3);
            step2.setImageResource(R.mipmap.zhifubao_step1);
            step3.setImageResource(R.mipmap.zhifubao_step2);
        }
        employee_name.setTextColor(intColor);
        step.setBackgroundColor(intColor);
        pay_method_text.setTextColor(intColor);
        pay_method_text.setText(payMethod);
        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .placeholder(R.mipmap.goods_place)
                .into(code);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void showShareView() {
        share_relative.setVisibility(View.VISIBLE);
    }

    @Override
    public void goToOrderActivity() {
        IntentStart.getInstance().startOrderActivity(getActivity());
        getActivity().finish();
    }

    //将条件置为未选择
    private void setUnSelect(List<Action> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIsSelect(false);
        }
    }

    //大转盘抽奖返回
    public void onEventMainThread(EventLottery eventLottery) {
        if (eventLottery != null && eventLottery.getType().equals(GlobalConstant.FragmentType.ORDERPAYFRAGMENT)) {
            for (int i = 0; i < mPresenter.getConsumerActionData().size(); i++) {
                Action action = mPresenter.getConsumerActionData().get(i);
                if (action.isSelect() && action.getType().equals(GlobalConstant.consumerConditionType.LOTTERYACTION)) {
                    action.setIsUsed(true);
                }
            }
            lotteryModel = eventLottery.getLotteryModel();
            doActions();
        }
    }

    //扫码返回微信卡卷
    public void onEventMainThread(EventScanCode eventScanCode) {
        if (eventScanCode != null && eventScanCode.getFragmentType().equals(GlobalConstant.FragmentType.ORDERPAYFRAGMENT)) {
            mPresenter.getWenChat(eventScanCode.getCode(), allOrder.getOrderNumber(), allOrder.getOrderPrice().toString());
        }
    }

    //抽奖结果中断
    public void onEventMainThread(EventActionFinish eventActionFinish) {
        if (eventActionFinish != null && eventActionFinish.isFinish() &&
                eventActionFinish.getType().equals(GlobalConstant.FragmentType.ORDERPAYFRAGMENT)) {
            showConditionDialog();
        }
    }

    //分享
    private void getshare(int type, RsOrderShareResponse response) {
        if (response == null) {
            showMessage("获取分享链接失败");
            return;
        }
        if (response.getUrl() == null) {
            showMessage("获取分享链接失败");
            return;
        }
        share(type, response.getUrl());
    }

    private void share(int type, String url) {
        //缩略图
        UMImage image = new UMImage(getActivity(), R.drawable.share);
        //连接
        UMWeb web = new UMWeb(url);
        web.setTitle("欧普");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("欧普照明零售全渠道营销平台");//描述
        switch (type) {
            case 1:
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
            case 2:
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
            case 3:
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.SINA)
                        .withMedia(web)
                        .setCallback(umShareListener)
                        .share();
                break;
        }
    }

    //支付完成结果页面
    @Override
    public void showResultDialog() {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.result_dialog, null);
        TextView content = (TextView) layout.findViewById(R.id.content);
        View line1 = (View) layout.findViewById(R.id.line1);
        line1.setVisibility(View.VISIBLE);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        cancel.setVisibility(View.VISIBLE);
        TextView confirm = (TextView) layout.findViewById(R.id.confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mPresenter.getGuideActionData().size(); i++) {
            if (mPresenter.getGuideActionData().get(i).getDescription() != null) {
                stringBuilder.append(mPresenter.getGuideActionData().get(i).getDescription() + ",");
            }
        }
 /*       for (int j = 0; j < mPresenter.getConsumerActionData().size(); j++) {
            if (mPresenter.getConsumerActionData().get(j).getType() == null) {
                continue;
            }
            if (mPresenter.getConsumerActionData().get(j).getType().equals(GlobalConstant.consumerConditionType.GOODSACTION)) {
                if (mPresenter.getConsumerActionData().get(j).getDescription() != null) {
                    stringBuilder.append(mPresenter.getConsumerActionData().get(j).getDescription());
                }
            }
        }*/
        stringBuilder.append("已发送到您的账户");
        content.setText(stringBuilder.toString());
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventMine eventMine = new EventMine();
                eventMine.setIsreflash(true);
                EventBus.getDefault().post(eventMine);
                getActivity().finish();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToOrderActivity();
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void showOrderPromotionContent() {
        order_promotion_linear.setVisibility(View.VISIBLE);
        List<OrderPromotionModel> orderPromotionModelList = new ArrayList<>();
        for (int i = 0; i < mPresenter.getOrderPromotionData().size(); i++) {
            TOOrderPromotionEntity toOrderPromotionEntity = mPresenter.getOrderPromotionData().get(i);
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.DISCOUNTACTION)) {
                OrderPromotionModel orderPromotionModel1 = new OrderPromotionModel();
                orderPromotionModel1.setTitle("转盘抽奖");
                orderPromotionModel1.setContent(toOrderPromotionEntity.getDiscountRate().divide(new BigDecimal(10)).toString() + "折");
                orderPromotionModelList.add(orderPromotionModel1);
            }
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.DEDUCTIONACTION)) {
                OrderPromotionModel orderPromotionModel2 = new OrderPromotionModel();
                orderPromotionModel2.setTitle("抵扣金额");
                orderPromotionModel2.setContent(BigDecimalUtils.forMate(toOrderPromotionEntity.getPromotionMoney()).toString());
                orderPromotionModelList.add(orderPromotionModel2);
            }
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                OrderPromotionModel orderPromotionModel3 = new OrderPromotionModel();
                orderPromotionModel3.setTitle("微信卡卷抵扣金额");
                orderPromotionModel3.setContent(BigDecimalUtils.forMate(new BigDecimal(toOrderPromotionEntity.getWxcardDenomation())).toString());
                orderPromotionModelList.add(orderPromotionModel3);
            }
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.GOODSACTION)) {
                OrderPromotionModel orderPromotionModel4 = new OrderPromotionModel();
                orderPromotionModel4.setTitle("赠送商品");
                orderPromotionModel4.setContent(toOrderPromotionEntity.getGoodsName());
                orderPromotionModelList.add(orderPromotionModel4);
            }
        }
        try {
            //对商品促销进行排序
            sortByPriority(mPresenter.getOrderPromotionData());
            //计算总金额的结果
            String totalDetail = getTotalDetail(allOrderBill.getOrderdetailList(), mPresenter.getOrderPromotionData());
            total_detail.setText(totalDetail);
            orderPromotionAdapter = new OrderPromotionAdapter(getActivity(), orderPromotionModelList);
            order_promotion_my_list_view.setAdapter(orderPromotionAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //计算最后的总价格
    private BigDecimal getFinalTotal(BigDecimal bigDecimal) {
        BigDecimal bigDecimalTotal = bigDecimal;

        for (int i = 0; i < mPresenter.getConsumerActionData().size(); i++) {
            Action action = mPresenter.getConsumerActionData().get(i);
            if (action.isSelect() && action.isUsed()) {
                //大转盘抽奖
                if (action.getType().equals(GlobalConstant.consumerConditionType.LOTTERYACTION)) {
                    if (lotteryModel != null) {
                        bigDecimalTotal = bigDecimalTotal.multiply(new BigDecimal(lotteryModel.getNumber())).divide(new BigDecimal(100));
                    }
                }
                //微信卡卷
                if (action.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                    if (mPresenter.getWeChatData() != null) {
                        bigDecimalTotal = bigDecimalTotal.subtract(new BigDecimal(mPresenter.getWeChatData().getDenomation()));
                    }
                }
                //抵扣
                if (action.getType().equals(GlobalConstant.consumerConditionType.DEDUCTIONACTION)) {
                    bigDecimalTotal = bigDecimalTotal.subtract(new BigDecimal(action.getTotal()));
                }
            }
        }
        return bigDecimalTotal;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //根据TOOrderPromotionEntity里面的Priority排序(冒泡排序,从大到小)
    private void sortByPriority(List<TOOrderPromotionEntity> list) {
        TOOrderPromotionEntity[] courseTopics = list.toArray(new TOOrderPromotionEntity[list.size()]);
        TOOrderPromotionEntity temp; // 记录临时中间值
        for (int i = 0; i < courseTopics.length - 1; i++) {
            for (int j = i + 1; j < courseTopics.length; j++) {
                if (courseTopics[i].getPrority().intValue() < courseTopics[j].getPrority().intValue()) { // 交换两数的位置
                    temp = courseTopics[i];
                    courseTopics[i] = courseTopics[j];
                    courseTopics[j] = temp;
                }
            }
        }
        list.clear();
        list.addAll(Arrays.asList(courseTopics));
    }

    //计算结果
    private String getTotalDetail(List<TOOrderdetailEntity> toOrderdetailEntityList, List<TOOrderPromotionEntity> list) {
        BigDecimal bigDecimalTotal = new BigDecimal(0);
        for (int j = 0; j < toOrderdetailEntityList.size(); j++) {
            TOOrderdetailEntity toOrderdetailEntity = toOrderdetailEntityList.get(j);
            BigDecimal bigDec = toOrderdetailEntity.getGoodsPrice().multiply(new
                    BigDecimal(toOrderdetailEntity.getGoodsNum()));
            bigDecimalTotal = bigDecimalTotal.add(bigDec);
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(" + BigDecimalUtils.forMate(bigDecimalTotal));
        for (int i = 0; i < list.size(); i++) {
            TOOrderPromotionEntity toOrderPromotionEntity = list.get(i);
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.DISCOUNTACTION)) {
                stringBuilder.append("*" + toOrderPromotionEntity.getDiscountRate().divide(new BigDecimal(100)).toString());
            }
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.DEDUCTIONACTION)) {
                stringBuilder.append("-" + toOrderPromotionEntity.getPromotionMoney().toString());
            }
            if (toOrderPromotionEntity.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                stringBuilder.append("-" + toOrderPromotionEntity.getWxcardDenomation());
            }
        }
        stringBuilder.append(")");
        return stringBuilder.toString();
    }
}
